#include "gw_grayscale_sensor.h"

volatile int ret_transmit, ret_receive;
uint8_t recv_value = 0;
uint8_t i2c_cmd;
volatile uint8_t sensor1, sensor2, sensor3, sensor4, sensor5, sensor6, sensor7, sensor8;
volatile uint8_t sensor_buffer[9] = {0, 0, 0, 0, 0, 0, 0,0,0}; // 用于存储传感器数据


/* 8MHz 5us大概是27, 64MHz 5us大概是270 */
static void delay(uint32_t delay_count)
{
	for (int i = 0; i < delay_count; ++i) {
		__NOP();
	}
}

void sensor_init()
{
	i2c_cmd = GW_GRAY_DIGITAL_MODE;
	ret_transmit = HAL_I2C_Master_Transmit(&hi2c3, GW_GRAY_ADDR_DEF << 1, &i2c_cmd, 1, 100);
}

void sensor_read(void)
{
	//printf("Tick %d\n", HAL_GetTick());
	
    ret_receive = HAL_I2C_Master_Receive(&hi2c3, GW_GRAY_ADDR_DEF << 1, &recv_value, 1, 100);
    SEP_ALL_BIT8(recv_value, sensor1, sensor2, sensor3, sensor4,sensor5, sensor6, sensor7, sensor8); // 0为黑线
	sensor_buffer[1] = sensor1;
	sensor_buffer[2] = sensor2;
	sensor_buffer[3] = sensor3;
	sensor_buffer[4] = sensor4;
	sensor_buffer[5] = sensor5;
	sensor_buffer[6] = sensor6;
	sensor_buffer[7] = sensor7;
	sensor_buffer[8] = sensor8;
	//printf("%d %d %d %d %d %d %d %d %d\n", sensor1, sensor2, sensor3, sensor4, sensor5, sensor6, sensor7, sensor8);

}
//计算八路传感器偏移量。 其中0代表黑线，1代表白色地图背景，数组下标从0开始
float cal_sensor_offset(void)
{
	float offset = 0.0;
	int8_t sum = 0;
	for (int i = 1; i <= 8; i++)
	{
		sum += sensor_buffer[i];
	}
	if ((8-sum) == 2) //检测到相邻2个传感器在黑线上
	{
		for (int i = 1; i <= 8; i++)
		{
			if (sensor_buffer[i] == 0 && sensor_buffer[i + 1] == 0)
			{
				offset = i - 4; // 计算偏移量
				break;
			}
		}
	}
	else if ((8-sum) >= 3) // 检测到3个及以上传感器在黑线上
	{
		offset = 0; // 偏移量为0

	}
	else if ((8-sum) == 1) // 只检测到1个传感器在黑线上
	{
		for (int i = 1; i <= 8; i++)
		{
			if (sensor_buffer[i] == 0)
			{
				offset = i - 4.5; // 计算偏移量
				break;
			}
		}
	}
	else // 没有检测到黑线
	{
		offset = 0; // 偏移量为0
	}
	return offset; // 返回偏移量
}

uint8_t gw_gray_serial_read()
{
	uint8_t ret = 0;

	for (int i = 0; i < 8; ++i) {
		/* 输出时钟下降沿 */
		HAL_GPIO_WritePin(GW_GRAY_SERIAL_GPIO_GROUP_CLK, GW_GRAY_SERIAL_GPIO_CLK, 0);
		delay(GW_GRAY_SERIAL_DELAY_VALUE); // 外部有上拉源(大约10k电阻) 可不加此行

		ret |= HAL_GPIO_ReadPin(GW_GRAY_SERIAL_GPIO_GROUP_DAT, GW_GRAY_SERIAL_GPIO_DAT) << i;

		/* 输出时钟上升沿,让传感器更新数据*/
		HAL_GPIO_WritePin(GW_GRAY_SERIAL_GPIO_GROUP_CLK, GW_GRAY_SERIAL_GPIO_CLK, 1);

		/* 主控频率高的需要给一点点延迟,延迟需要在5us左右 */
		delay(GW_GRAY_SERIAL_DELAY_VALUE);
	}
    SEP_ALL_BIT8(ret,sensor_buffer[1], sensor_buffer[2], sensor_buffer[3], sensor_buffer[4],
				 sensor_buffer[5], sensor_buffer[6], sensor_buffer[7], sensor_buffer[8]);
	return ret;
}
